# -*- coding: utf-8 -*-
from __future__ import absolute_import

import re

from PyQt4.QtCore import QObject
from PyQt4.QtCore import QSettings
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QInputDialog
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QShortcut

from ninja_ide.core import file_manager
from ninja_ide.core import settings
from ninja_ide import resources
import webbrowser
from ninja_ide.tools import ui_tools
from ninja_ide.tools import locator
from ninja_ide.tools import json_manager
from ninja_ide.tools import introspection
from ninja_ide.gui.editor import helpers
from ninja_ide.gui.dialogs import from_import_dialog


__actionsInstance = None


def Actions(*args, **kw):
    global __actionsInstance
    if __actionsInstance is None:
        __actionsInstance = __Actions(*args, **kw)
    return __actionsInstance


class __Actions(QObject):

    def __init__(self):
        QObject.__init__(self)
        #Definition Locator
        self._locator = locator.Locator()
        self.__codeBack = []
        self.__codeForward = []
        self.__bookmarksFile = ''
        self.__bookmarksPos = -1
        self.__breakpointsFile = ''
        self.__breakpointsPos = -1
        self.__operations = {
            0: self._navigate_code_jumps,
            1: self._navigate_bookmarks,
            2: self._navigate_breakpoints}

    def install_shortcuts(self, ide):
        self._ide = ide
        short = resources.get_shortcut
        self.shortDuplicate = QShortcut(short("Duplicate"), self._ide)
        self.shortRemove = QShortcut(short("Remove-line"), self._ide)
        self.shortMoveUp = QShortcut(short("Move-up"), self._ide)
        self.shortMoveDown = QShortcut(short("Move-down"), self._ide)
        self.shortCloseTab = QShortcut(short("Close-tab"), self._ide)
        self.shortNew = QShortcut(short("New-file"), self._ide)
        self.shortNewProject = QShortcut(short("New-project"), self._ide)
        self.shortOpen = QShortcut(short("Open-file"), self._ide)
        self.shortOpenProject = QShortcut(short("Open-project"), self._ide)
        self.shortSave = QShortcut(short("Save-file"), self._ide)
        self.shortSaveProject = QShortcut(short("Save-project"), self._ide)
        self.shortPrint = QShortcut(short("Print-file"), self._ide)
        self.shortRedo = QShortcut(short("Redo"), self._ide)
        self.shortComment = QShortcut(short("Comment"), self._ide)
        self.shortHorizontalLine = QShortcut(short("Horizontal-line"),
            self._ide)
        self.shortTitleComment = QShortcut(short("Title-comment"), self._ide)
        self.shortIndentLess = QShortcut(short("Indent-less"), self._ide)
        self.shortHideMisc = QShortcut(short("Hide-misc"), self._ide)
        self.shortHideEditor = QShortcut(short("Hide-editor"), self._ide)
        self.shortHideExplorer = QShortcut(short("Hide-explorer"), self._ide)
        self.shortRunFile = QShortcut(short("Run-file"), self._ide)
        self.shortRunProject = QShortcut(short("Run-project"), self._ide)
        self.shortStopExecution = QShortcut(short("Stop-execution"), self._ide)
        self.shortHideAll = QShortcut(short("Hide-all"), self._ide)
        self.shortFullscreen = QShortcut(short("Full-screen"), self._ide)
        self.shortFind = QShortcut(short("Find"), self._ide)
        self.shortFindReplace = QShortcut(short("Find-replace"), self._ide)
        self.shortFindWithWord = QShortcut(short("Find-with-word"), self._ide)
        self.shortHelp = QShortcut(short("Help"), self._ide)
        self.shortSplitHorizontal = QShortcut(short("Split-horizontal"),
            self._ide)
        self.shortSplitVertical = QShortcut(short("Split-vertical"), self._ide)
        self.shortFollowMode = QShortcut(short("Follow-mode"), self._ide)
        self.shortReloadFile = QShortcut(short("Reload-file"), self._ide)
        self.shortShowProjectsTree = QShortcut(short("Show-project-tree"),
            self._ide)
        self.shortShowSymbolsTree = QShortcut(short("Show-symbols-tree"),
            self._ide)
        self.shortShowWebInspector = QShortcut(short("Show-web-inspector"),
            self._ide)
        self.shortJump = QShortcut(short("Jump"), self._ide)
        self.shortFindInFiles = QShortcut(short("Find-in-files"), self._ide)
        self.shortImport = QShortcut(short("Import"), self._ide)
        self.shortGoToDefinition = QShortcut(short("Go-to-definition"),
            self._ide)
        self.shortCodeLocator = QShortcut(short("Code-locator"), self._ide)
        self.shortNavigateBack = QShortcut(short("Navigate-back"), self._ide)
        self.shortNavigateForward = QShortcut(short("Navigate-forward"),
            self._ide)

        #Connect Shortcuts Signals
        self.connect(self.shortNavigateBack, SIGNAL("activated()"),
            lambda: self.__navigate_with_keyboard(False))
        self.connect(self.shortNavigateForward, SIGNAL("activated()"),
            lambda: self.__navigate_with_keyboard(True))
        self.connect(self.shortCodeLocator, SIGNAL("activated()"),
            self._ide._status.show_locator)
        self.connect(self.shortGoToDefinition, SIGNAL("activated()"),
            self._editor_go_to_definition)
        self.connect(self.shortRedo, SIGNAL("activated()"),
            self._editor_redo)
        self.connect(self.shortHorizontalLine, SIGNAL("activated()"),
            self._editor_insert_horizontal_line)
        self.connect(self.shortTitleComment, SIGNAL("activated()"),
            self._editor_insert_title_comment)
        self.connect(self.shortFollowMode, SIGNAL("activated()"),
            self._ide._mainContainer.show_follow_mode)
        self.connect(self.shortReloadFile, SIGNAL("activated()"),
            self._ide._mainContainer.reload_file)
        self.connect(self.shortSplitHorizontal, SIGNAL("activated()"),
            lambda: self._ide._mainContainer.split_tab(True))
        self.connect(self.shortSplitVertical, SIGNAL("activated()"),
            lambda: self._ide._mainContainer.split_tab(False))
        self.connect(self.shortNew, SIGNAL("activated()"),
            self._ide._mainContainer.add_editor)
        self.connect(self.shortNewProject, SIGNAL("activated()"),
            self._ide._explorer.create_new_project)
        self.connect(self.shortHideMisc, SIGNAL("activated()"),
            self._ide._central.change_misc_visibility)
        self.connect(self.shortHideEditor, SIGNAL("activated()"),
            self._ide._central.change_main_visibility)
        self.connect(self.shortHideExplorer, SIGNAL("activated()"),
            self._ide._central.change_explorer_visibility)
        self.connect(self.shortHideAll, SIGNAL("activated()"),
            self._hide_all)
        self.connect(self.shortJump, SIGNAL("activated()"),
            self._ide._mainContainer.editor_jump_to_line)
        self.connect(self.shortFullscreen, SIGNAL("activated()"),
            self._fullscreen_mode)
        self.connect(self.shortShowSymbolsTree, SIGNAL("activated()"),
            self._ide._explorer.show_symbols_tree)
        self.connect(self.shortShowProjectsTree, SIGNAL("activated()"),
            self._ide._explorer.show_project_tree)
        self.connect(self.shortShowWebInspector, SIGNAL("activated()"),
            self._ide._explorer.show_web_inspector)
        self.connect(self.shortOpen, SIGNAL("activated()"),
            self._ide._mainContainer.open_file)
        self.connect(self.shortOpenProject, SIGNAL("activated()"),
            self.open_project)
        self.connect(self.shortCloseTab, SIGNAL("activated()"),
            self._ide._mainContainer._actualTab.close_tab)
        self.connect(self.shortSave, SIGNAL("activated()"),
            self._ide._mainContainer.save_file)
        self.connect(self.shortSaveProject, SIGNAL("activated()"),
            self.save_project)
        self.connect(self.shortPrint, SIGNAL("activated()"),
            self.print_file)
        self.connect(self.shortFind, SIGNAL("activated()"),
            self._ide._status.show)
        self.connect(self.shortFindWithWord, SIGNAL("activated()"),
            self._ide._status.show_with_word)
        self.connect(self.shortFindReplace, SIGNAL("activated()"),
            self._ide._status.show_replace)
        self.connect(self.shortRunFile, SIGNAL("activated()"),
            self._execute_file)
        self.connect(self.shortRunProject, SIGNAL("activated()"),
            self._execute_project)
        self.connect(self.shortStopExecution, SIGNAL("activated()"),
            self._kill_execution)
        self.connect(self.shortIndentLess, SIGNAL("activated()"),
            self._editor_indent_less)
        self.connect(self.shortComment, SIGNAL("activated()"),
            self._editor_comment)
        self.connect(self.shortHelp, SIGNAL("activated()"),
            self._ide._mainContainer.show_python_doc)
        self.connect(self.shortImport, SIGNAL("activated()"),
            self.import_from_everywhere)
        self.connect(self.shortFindInFiles, SIGNAL("activated()"),
            self._ide._misc.show_find_in_files_widget)
        self.connect(self.shortMoveUp, SIGNAL("activated()"),
            self._editor_move_up)
        self.connect(self.shortMoveDown, SIGNAL("activated()"),
            self._editor_move_down)
        self.connect(self.shortRemove, SIGNAL("activated()"),
            self._editor_remove_line)
        self.connect(self.shortDuplicate, SIGNAL("activated()"),
            self._editor_duplicate)

        #Connect SIGNALs from other objects
        self.connect(self._ide._mainContainer._tabMain,
            SIGNAL("runFile()"), self._execute_file)
        self.connect(self._ide._mainContainer._tabSecondary,
            SIGNAL("runFile()"), self._execute_file)
        self.connect(self._ide._mainContainer._tabMain,
            SIGNAL("addToProject(QString)"), self._add_file_to_project)
        self.connect(self._ide._mainContainer._tabSecondary,
            SIGNAL("addToProject(QString)"), self._add_file_to_project)
        self.connect(self._ide._mainContainer,
            SIGNAL("openProject(QString)"), self.open_project)

    def update_shortcuts(self):
        resources.load_shortcuts()
        short = resources.get_shortcut
        self.shortDuplicate.setKey(short("Duplicate"))
        self.shortRemove.setKey(short("Remove-line"))
        self.shortMoveUp.setKey(short("Move-up"))
        self.shortMoveDown.setKey(short("Move-down"))
        self.shortCloseTab.setKey(short("Close-tab"))
        self.shortNew.setKey(short("New-file"))
        self.shortNewProject.setKey(short("New-project"))
        self.shortOpen.setKey(short("Open-file"))
        self.shortOpenProject.setKey(short("Open-project"))
        self.shortSave.setKey(short("Save-file"))
        self.shortSaveProject.setKey(short("Save-project"))
        self.shortPrint.setKey(short("Print-file"))
        self.shortRedo.setKey(short("Redo"))
        self.shortComment.setKey(short("Comment"))
        self.shortHorizontalLine.setKey(short("Horizontal-line"))
        self.shortTitleComment.setKey(short("Title-comment"))
        self.shortIndentLess.setKey(short("Indent-less"))
        self.shortHideMisc.setKey(short("Hide-misc"))
        self.shortHideEditor.setKey(short("Hide-editor"))
        self.shortHideExplorer.setKey(short("Hide-explorer"))
        self.shortRunFile.setKey(short("Run-file"))
        self.shortRunProject.setKey(short("Run-project"))
        self.shortStopExecution.setKey(short("Stop-execution"))
        self.shortHideAll.setKey(short("Hide-all"))
        self.shortFullscreen.setKey(short("Full-screen"))
        self.shortFind.setKey(short("Find"))
        self.shortFindReplace.setKey(short("Find-replace"))
        self.shortFindWithWord.setKey(short("Find-with-word"))
        self.shortHelp.setKey(short("Help"))
        self.shortSplitHorizontal.setKey(short("Split-horizontal"))
        self.shortSplitVertical.setKey(short("Split-vertical"))
        self.shortFollowMode.setKey(short("Follow-mode"))
        self.shortReloadFile.setKey(short("Reload-file"))
        self.shortShowProjectsTree.setKey(short("Show-project-tree"))
        self.shortShowSymbolsTree.setKey(short("Show-symbols-tree"))
        self.shortShowWebInspector.setKey(short("Show-web-inspector"))
        self.shortJump.setKey(short("Jump"))
        self.shortFindInFiles.setKey(short("Find-in-files"))
        self.shortImport.setKey(short("Import"))
        self.shortGoToDefinition.setKey(short("Go-to-definition"))
        self.shortCodeLocator.setKey(short("Code-locator"))
        self.shortNavigateBack.setKey(short("Navigate-back"))
        self.shortNavigateForward.setKey(short("Navigate-forward"))

    def __navigate_with_keyboard(self, val):
        op = self._ide._mainContainer._tabMain.navigator.operation
        self.navigate_code_history(val, op)

    def _add_file_to_project(self, path):
        pathProject = self._ide._explorer.get_actual_project()
        addToProject = ui_tools.AddToProject(pathProject, self._ide)
        addToProject.exec_()
        if not addToProject.pathSelected:
            return
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if not editorWidget.ID:
            name = unicode(QInputDialog.getText(None,
                self.tr("Add File To Project"), self.tr("File Name:"))[0])
            if not name:
                QMessageBox.information(self, self.tr("Indalid Name"),
                    self.tr("The file name is empty, please enter a name"))
                return
        else:
            name = file_manager.get_basename(editorWidget.ID)
        path = file_manager.create_abs_path(
            unicode(addToProject.pathSelected), name)
        if not file_manager.file_exists(path):
            path = file_manager.store_file_content(
                path, editorWidget.get_text())
            editorWidget.ID = path
            self._ide._explorer.add_existing_file(path)
            self._ide.change_window_title(path)
            name = file_manager.get_basename(path)
            self._ide._mainContainer._actualTab.setTabText(
                self._ide._mainContainer._actualTab.currentIndex(), name)
            editorWidget._file_saved()
        else:
            QMessageBox.information(self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file already exists."))

    def import_from_everywhere(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            text = unicode(editorWidget.get_text())
            froms = re.findall('^from (.*)', text, re.MULTILINE)
            fromSection = list(set([f.split(' import')[0] for f in froms]))
            dialog = from_import_dialog.FromImportDialog(fromSection,
                editorWidget, self._ide)
            dialog.show()

    def open_project(self, path=''):
        self._ide._explorer.open_project_folder(unicode(path))
        self._ide._status.explore_code()

    def save_profile(self):
        profileInfo = QInputDialog.getText(None,
            self.tr("Create Profile"), self.tr("Profile Name:"))
        if profileInfo[1]:
            profileName = unicode(profileInfo[0])
            if not profileName or profileName in settings.PROFILES:
                QMessageBox.information(self, self.tr("Profile Name Invalid"),
                    self.tr("The Profile name is invalid or already exists."))
                return
            projects = self._ide._explorer.get_opened_projects()
            settings.PROFILES[profileName] = projects
            qsettings = QSettings()
            qsettings.setValue('ide/profiles', settings.PROFILES)

    def open_profile(self):
        profilesLoader = ui_tools.ProfilesLoader(self.load_profile_data,
            settings.PROFILES, self._ide)
        profilesLoader.show()

    def load_profile_data(self, key):
        self._ide._explorer.close_opened_projects()
        self._ide._explorer.open_session_projects(settings.PROFILES[key])
        self._ide._status.explore_code()

    def count_file_code_lines(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            blanks = re.findall('(^\n)|(^(\s+)?#)|(^( +)?($|\n))',
                unicode(editorWidget.get_text()), re.M)
            resume = self.tr("Lines code: %1\n").arg(
                editorWidget.blockCount() - len(blanks))
            resume += self.tr("Blanks and commented lines: %1\n\n").arg(
                len(blanks))
            resume += self.tr("Total lines: %1").arg(editorWidget.blockCount())
            msgBox = QMessageBox(QMessageBox.Information,
                self.tr("Summary of lines"), resume,
                QMessageBox.Ok, editorWidget)
            msgBox.exec_()

    def _execute_file(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            if not editorWidget.ID:
                self._ide._mainContainer.save_file()
            ext = file_manager.get_file_extension(editorWidget.ID)
            if ext == '.py':
                self._ide._misc.run_application(editorWidget.ID)
            elif ext == '.html':
                self._ide._misc.render_web_page(editorWidget.ID)

    def _execute_project(self):
        mainFile = self._ide._explorer.get_project_main_file()
        if not mainFile and self._ide._explorer._treeProjects and \
        self._ide._explorer._treeProjects._actualProject:
            self._ide._explorer._treeProjects.open_project_properties()
        elif mainFile:
            self.save_project()
            path = self._ide._explorer.get_actual_project()
            project = json_manager.read_ninja_project(path)
            venv = project.get('venv', False)
            mainFile = file_manager.create_abs_path(path, mainFile)
            self._ide._misc.run_application(mainFile, pythonPath=venv)

    def _kill_execution(self):
        self._ide._misc.kill_application()

    def _fullscreen_mode(self):
        if self._ide.isFullScreen():
            self._ide.showMaximized()
        else:
            self._ide.showFullScreen()

    def _editor_redo(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            editorWidget.redo()

    def _editor_indent_less(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            editorWidget.indent_less()

    def _editor_indent_more(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            editorWidget.indent_more()

    def _editor_comment(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.comment(editorWidget)

    def _editor_insert_horizontal_line(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.insert_horizontal_line(editorWidget)

    def _editor_insert_title_comment(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.insert_title_comment(editorWidget)

    def _editor_remove_trailing_spaces(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.remove_trailing_spaces(editorWidget)

    def _editor_replace_tabs_with_spaces(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.replace_tabs_with_spaces(editorWidget)

    def _editor_move_up(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.move_up(editorWidget)

    def _editor_move_down(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.move_down(editorWidget)

    def _editor_remove_line(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.remove_line(editorWidget)

    def _editor_duplicate(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            helpers.duplicate(editorWidget)

    def _editor_go_to_definition(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            editorWidget.go_to_definition()

    def _editor_go_to_line(self, line):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            editorWidget.jump_to_line(line)

    def reset_editor_flags(self):
        self._ide._mainContainer.reset_editor_flags()

    def preview_in_browser(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            if not editorWidget.ID:
                self._ide._mainContainer.save_file()
            ext = file_manager.get_file_extension(editorWidget.ID)
            if ext == '.html':
                webbrowser.open(editorWidget.ID)

    def _hide_all(self):
        if self._ide.menuBar().isVisible():
            self._ide._explorer.hide()
            self._ide._misc.hide()
            self._ide._toolbar.hide()
            self._ide.menuBar().hide()
        else:
            self._ide._explorer.show()
            self._ide._toolbar.show()
            self._ide.menuBar().show()

    def save_project(self):
        path = self._ide._explorer.get_actual_project()
        if path:
            self._ide._mainContainer.save_project(path)

    def print_file(self):
        """Call the print of ui_tool

        Call print of ui_tool depending on the focus of the application"""
        #TODO: Add funtionality for proyect tab and methods tab
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget is not None:
            fileName = "newDocument.pdf"
            if editorWidget.ID:
                fileName = file_manager.get_basename(
                    editorWidget.ID)
                fileName = fileName[:fileName.rfind('.')] + '.pdf'
            ui_tools.print_file(fileName, editorWidget.print_)

    def locate_function(self, function, filePath, isVariable):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            self.__codeBack.append((editorWidget.ID,
                editorWidget.textCursor().position()))
            self.__codeForward = []
        self._locator.navigate_to(unicode(function),
            unicode(filePath), isVariable)

    def update_explorer(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            source = unicode(editorWidget.toPlainText())
            symbols = introspection.obtain_symbols(source)
            self._ide._explorer.update_symbols(symbols)
            self._ide._explorer.update_errors(
                editorWidget.errors, editorWidget.pep8)

    def navigate_code_history(self, val, op):
        self.__operations[op](val)

    def _navigate_code_jumps(self, val):
        node = None
        if not val and self.__codeBack:
            node = self.__codeBack.pop()
            editorWidget = self._ide._mainContainer.get_actual_editor()
            if editorWidget:
                self.__codeForward.append((editorWidget.ID,
                    editorWidget.textCursor().position()))
        elif val and self.__codeForward:
            node = self.__codeForward.pop()
            editorWidget = self._ide._mainContainer.get_actual_editor()
            if editorWidget:
                self.__codeBack.append((editorWidget.ID,
                    editorWidget.textCursor().position()))
        if node:
            self._ide._mainContainer.open_file(node[0], None, node[1])

    def _navigate_breakpoints(self, val):
        breakList = settings.BREAKPOINTS.keys()
        breakList.sort()
        if not breakList:
            return
        if self.__breakpointsFile not in breakList:
            self.__breakpointsFile = breakList[0]
        index = breakList.index(self.__breakpointsFile)
        breaks = settings.BREAKPOINTS[self.__breakpointsFile]
        lineNumber = 0
        #val == True: forward
        if val:
            if (len(breaks) - 1) > self.__breakpointsPos:
                self.__breakpointsPos += 1
                lineNumber = breaks[self.__breakpointsPos]
            else:
                if index < (len(breakList) - 1):
                    self.__breakpointsFile = breakList[index + 1]
                else:
                    self.__breakpointsFile = breakList[0]
                self.__breakpointsPos = 0
                breaks = settings.BREAKPOINTS[self.__breakpointsFile]
                lineNumber = breaks[0]
        else:
            if self.__breakpointsPos > 0:
                self.__breakpointsPos -= 1
                lineNumber = breaks[self.__breakpointsPos]
            else:
                self.__breakpointsFile = breakList[index - 1]
                breaks = settings.BREAKPOINTS[self.__breakpointsFile]
                self.__breakpointsPos = len(breaks) - 1
                lineNumber = breaks[self.__breakpointsPos]
        self._ide._mainContainer.open_file(self.__breakpointsFile,
            None, lineNumber, None, True)

    def _navigate_bookmarks(self, val):
        bookList = settings.BOOKMARKS.keys()
        bookList.sort()
        if not bookList:
            return
        if self.__bookmarksFile not in bookList:
            self.__bookmarksFile = bookList[0]
        index = bookList.index(self.__bookmarksFile)
        bookms = settings.BOOKMARKS[self.__bookmarksFile]
        lineNumber = 0
        #val == True: forward
        if val:
            if (len(bookms) - 1) > self.__bookmarksPos:
                self.__bookmarksPos += 1
                lineNumber = bookms[self.__bookmarksPos]
            else:
                if index < (len(bookList) - 1):
                    self.__bookmarksFile = bookList[index + 1]
                else:
                    self.__bookmarksFile = bookList[0]
                self.__bookmarksPos = 0
                bookms = settings.BOOKMARKS[self.__bookmarksFile]
                lineNumber = bookms[0]
        else:
            if self.__bookmarksPos > 0:
                self.__bookmarksPos -= 1
                lineNumber = bookms[self.__bookmarksPos]
            else:
                self.__bookmarksFile = bookList[index - 1]
                bookms = settings.BOOKMARKS[self.__bookmarksFile]
                self.__bookmarksPos = len(bookms) - 1
                lineNumber = bookms[self.__bookmarksPos]
        self._ide._mainContainer.open_file(self.__bookmarksFile,
            None, lineNumber, None, True)

    def add_back_item_navigation(self):
        editorWidget = self._ide._mainContainer.get_actual_editor()
        if editorWidget:
            self.__codeBack.append((editorWidget.ID,
                editorWidget.textCursor().position()))
            self.__codeForward = []
